<template>
  <div class="base-content WXOfficialBinding" >
    <div v-if="currentStep === 'begin'">
      <div class="before-begin" >
        <div class="wxkf-logo">
          <img src="../../../../../assets/img/wxkfLogo.png" alt=""/>
          <span>
              <p>
                {{$t('configLazyLoad.channel.WXkfAccess001')}}
              </p>
          </span>
        </div>
        <div class="WXOfficial_hint">
          <span v-html="$t('configLazyLoad.channel.WXkfAccess002')"></span><br/>
          {{$t('configLazyLoad.channel.WXkfAccess003')}}<br/>
          {{$t('configLazyLoad.channel.WXkfAccess004')}}
        </div>
      </div>
      <div class="search">
        <div class='fl'>
          <span class="icon-text" @click.stop="add"><i class="el-icon-plus"></i>{{$t('public.add')}}</span>
          <span class="icon-text" @click.stop="refresh"><i class="iconfont icon-shuaxin"></i>{{$t('public.refresh')}}</span>
          <span class="icon-text">{{$t('configLazyLoad.channel.AuthorizedEnterprise')}}：</span>
          <el-select size="mini" v-model="cropIdSearch" :placeholder="$t('public.pleasePick')" class="select" @change="searchByCropid">
            <el-option
              value=""
              :label="$t('public.all')">
            </el-option>
            <el-option
              v-for="item in authorizationArr"
              :key="item.corpid"
              :label="item.corpName"
              :value="item.corpid"
            >
            </el-option>
          </el-select>
        </div>
        <pagination class="page"
                    :small="true"
                    :currentPage="currentPage"
                    :count="count || 0"
                    :totalPage="Math.ceil(count / 10)"
                    @turnPage="turnPage">
        </pagination>
      </div>
      <el-table :data="tableData">
        <el-table-column prop="corpName" :label="$t('configLazyLoad.channel.AuthorizedEnterprise')">
        </el-table-column>
        <el-table-column prop="name" :label="$t('configLazyLoad.channel.WXkfScenes')">
        </el-table-column>
        <el-table-column prop="openKfName" :label="$t('configLazyLoad.channel.custAccount')">
        </el-table-column>
        <el-table-column prop="to_peer_name" :label="$t('public.queues')">
        </el-table-column>
        <el-table-column prop="robotName" :label="$t('config.channel.isUseRobt2')">
        </el-table-column>
        <el-table-column prop="lastUpdateTime" :label="$t('config.channel.lastUpdateTime')">
        </el-table-column>
        <el-table-column :label="$t('public.operate')">
          <template scope="scope">
            <el-button type="text" @click="edit(scope.row)" size="small">{{$t('public.edit')}}</el-button>
            <el-button type="text" @click="qrcodeFun(scope.row)" size="small">{{$t('public.test')}}</el-button>
            <el-button type="text" @click="access(scope.row)" size="small">{{$t('configLazyLoad.channel.WXkfAccess005')}}</el-button>
            <el-button type="text" class="delete_text" @click="deleteLi(scope.row)" size="small">{{$t('public.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="editCustomer" v-if="currentStep !== 'begin'">
      <bread-crumb :titleArr="titleArr" @back="back"></bread-crumb>
      <updateWXScenario @back="back" :data="updateData" v-if="currentStep === 'updateScenario'"></updateWXScenario>
      <accessConfig @back="back" :data="configData" v-if="currentStep === 'accessConfig'"></accessConfig>
    </div>
    <el-dialog 
      :title="$t('configLazyLoad.channel.WXkfAccess024')"
      :visible.sync="dialogVisible"
      width="30%"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
    >
      <qrcode-image
        class="qrcode_image_test"
        ref="qrcodeTest"
        :optionSize="350"
        :logoShow="false"
        :allAccessUrl="qrcodeUrl"
      >
      </qrcode-image>
    </el-dialog>
  </div>
</template>
<script>
import QrcodeImage from '../webCustomerService/webOnlineServer/QrcodeImage.vue'
import Pagination from '@/components/public-modules/card/Pagination'
import { deepClone, getFormatDateTime } from '@/utils/m7Utils'
import search from '../base/search.vue'
import breadCrumb from './../../../../ui-modules/breadCrumb/BreadCrumbConfig.vue'
import updateWXScenario from './updateWXScenario.vue'
import accessConfig from './wxkfAccessConfig.vue'
export default {
  name: 'accessScenario',
  data () {
    return {
      currentStep: 'begin',
      count: 0,
      cropIdData: '',
      authorizationArr: [],
      customerArr: [],
      currentPage: 1,
      cropIdSearch: '',
      robotOptions: [],
      peerOptions: [],
      tableData: [],
      updateData: {},
      configData: {},
      qrcodeUrl: "",
      dialogVisible: false,
      titleArr: [this.$t('configLazyLoad.channel.WXkfScenes'), this.$t('public.add')]
    }
  },
  methods: {
    back () {
      this.updateData = {}
      this.configData = {}
      this.currentStep = "begin"
      this.refresh()
    },
    add () {
      this.updateData = {}
      this.currentStep = "updateScenario"
      this.titleArr = [this.$t('configLazyLoad.channel.WXkfScenes'), this.$t('public.add')]
    },
    edit (data) {
      this.updateData = deepClone(data)
      this.currentStep = "updateScenario"
      this.titleArr = [this.$t('configLazyLoad.channel.WXkfScenes'), this.$t('public.edit')]
    },
    access (data) {
      this.titleArr = [this.$t('configLazyLoad.channel.WXkfScenes'), this.$t('configLazyLoad.channel.WXkfAccess005')]
      this.configData = deepClone(data)
      this.currentStep = "accessConfig"
    },
    deleteLi (data) {
      this.$confirm(this.$t('configLazyLoad.channel.WXkfAccess025'), this.$t('public.tip'), {
        confirmButtonText: this.$t('public.confirm'),
        cancelButtonText: this.$t('public.cancel'),
        cancelButtonClass: 'primary_btn',
        confirmButtonClass: 'primary_btn',
        type: 'warning'
      }).then(() => {
        var dataObj = {
          _id: data._id
        }
        this.$store.dispatch('removeWxkfConfig', dataObj).then((res) => {
          if (res && res.success) {
            this.$message.success(this.$t('config.channel.deleteSuccess'))
          } else {
            this.$message.error(this.$t('config.channel.deleteFailure'))
          }
          this.refresh()
        })
      })
    },
    qrcodeFun (data) {
      this.qrcodeUrl = data.kfUrl
      this.dialogVisible = true
    },
    refresh () {
      this.currentPage = 1
      this.cropIdSearch = ''
      this.search()
    },
    turnPage (val) {
      this.currentPage = val
      this.search()
    },
    search () {
      var data = {
        page: this.currentPage,
        limit: 10
      }
      if (this.cropIdSearch) {
        data.corpid = this.cropIdSearch
      }
      let that = this
      Promise.all([
        this.$store.dispatch('getWxkfWorkConfigs', {}),
        this.$store.dispatch('getWxkfConfigs', data)
      ]).then(([res1, res2]) => {
        if (res1 && res1.success) {
          if (res1.list) {
            this.authorizationArr = deepClone(res1.list)
            this.customerArr = []
            this.authorizationArr.forEach((item) => {
              if (item.kfAccountList && item.kfAccountList.length) {
                this.customerArr = deepClone(this.customerArr.concat(item.kfAccountList))
              }
            })
          } else {
            this.authorizationArr = []
            this.customerArr = []
          }
        }
        if (res2 && res2.success) {
          var dataArr = deepClone(res2.list)
          dataArr.forEach((item) => {
            if (item.updateTime) {
              var time = getFormatDateTime(new Date(item.updateTime))
              this.$set(item, 'lastUpdateTime', time)
            }
            var openKfName = ''
            if (that.customerArr && that.customerArr.length) {
              for (var i=0;i < that.customerArr.length;i++) {
                if (that.customerArr[i].open_kfid === item.openKfid) {
                  openKfName = that.customerArr[i].name
                  break
                }
              }
            }
            this.$set(item, 'openKfName', openKfName)
          })
          this.tableData = deepClone(dataArr)
          this.count = res2.count
        }
      })
    },
    // 根据Cropid查询接入场景
    searchByCropid (val) {
      this.cropIdSearch = val
      this.search()
    }
  },
  components: {
    search,
    breadCrumb,
    QrcodeImage,
    Pagination,
    updateWXScenario,
    accessConfig
  },
  mounted () {
    this.refresh()
  },
  beforeMount () {
    this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
      let mailQueues = this.$getCache('mailQueues')
      if (!mailQueues || mailQueues.length === 0) {
        return
      }
      this.peerOptions = mailQueues || []
    })
    //      获取机器人列表
    this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
      let robotConfig = this.$getCache('robotConfig')
      this.robotOptions = robotConfig || []
      this.$store.dispatch('queryM7AIRobot', {}).then((res2) => {
        if (res2 && res2.success && res2.data && res2.data.length > 0) {
          let configArr = []
          this.robotOptions.forEach((config) => {
            if (config.robot_type !== 'didi') {
              configArr.push(config)
            }
          })
          this.robotOptions = configArr.concat(this.aiRobots)
        }
      })
    })
  //   this.$store.dispatch("getWxkfWorkConfigs", {}).then(req => {
  //     if (req && req.success) {
  //       if (req.list) {
  //         this.authorizationArr = deepClone(req.list)
  //         this.customerArr = []
  //         debugger
  //         this.authorizationArr.forEach((item) => {
  //           if (item.kfAccountList && item.kfAccountList.length) {
  //             this.customerArr = deepClone(this.customerArr.concat(item.kfAccountList))
  //           }
  //         })
  //       } else {
  //         this.authorizationArr = []
  //         this.customerArr = []
  //       }
  //     }
  //   })
  }
}
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .base-content
    height calc(100vh - 170px)
    overflow-y auto
    text-align center
    .before-begin
      margin 25px
      background #f2f6fa
      >p
        margin-bottom 34px
        font-size 14px
        line-height 18px
      .el-button
        margin-bottom 28px
      .wxkf-logo
        padding 34px 0 10px 0
        display table
        margin 0 auto
        span
          display table-cell
          vertical-align middle
          margin-left 10px
          p
            line-height 1.8
            margin-left 14px
            text-align left
    .editCustomer
      padding 20px
      .breadCrumb
        text-align left
      .title
        font-size 24px
        font-weight 700px
        margin 20px 0
      .wechatType
        padding 20px
        text-align: center
        .wechatoption
          text-align left
          width 140px
          display inline-block
          p
            color $cf-gray4
            padding-left 20px
  .WXOfficial_hint
    text-align left
    display inline-block
    margin-bottom 20px
  .delete_text
    color #ff6b6b !important
  .qrcode_image_test
    display inline-block
    margin-right -20px
  .search
    height 30px
    padding 8px 10px
    border 1px solid #E7E7EB
    border-bottom none
    .el-icon-plus,.icon-shuaxin
      color $c-main
      font-size 12px
      margin-right 2px
    .select
      margin-right 20px
    .page
      float right
    .icon-text
      margin-right 16px
      cursor pointer
      line-height 30px
</style>